import request from '@/utils/request'

/**
 * 上传类请求方法
 */
export default class UploadService {

    
    /**
     * 错误提示
     * @param msg
     * @returns {{msg: string, code: number, data: []}}
     */
    error(msg = '上传出错') {
        return {code: 10001, msg: msg, data: []};
    }

    /**
     * 返回检查后的from
     * @param data
     * @returns {{msg: string, code: number, data: *}}
     */
    success(data) {
        return {code: 20000, msg: '', data: data};
    }

    /**
     * 上传前的检查
     * @param event
     * @returns {{msg: string, code: number, data: *}}
     */
    check(event) {
        let imgData = {
            accept: 'image/gif, image/jpeg, image/png, image/jpg',
        };
        let img = event.target.files[0];
        let type = img.type;//文件的类型，判断是否是图片
        let size = img.size;//文件的大小，判断图片的大小
        if (imgData.accept.indexOf(type) === -1) {
            this.error('请选择我们支持的图片格式！');
            return;
        }
        if (size > 3145728) {
            this.error('请选择3M以内的图片！');
            return;
        }

        let form = new FormData();
        form.append('file', img, img.name);
        return this.success(form);
    }

    /**
     * 提交上传信息
     * @param form
     * @returns {*}
     */
    post(form) {
        return request.post('/upload/file', form, {
            headers: {'Content-Type': 'multipart/form-data'}
        }).then(res => {
            return res;
        });
    }
}
